package model.feature;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

import model.Settings;
import model.inventory.FieldFormatMapper;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import util.LoggingUtils;
import util.PlayerUtilities;

public class FeatureDefinitionBuilder {
	public static final String MAIN_IMAGE_CONTAINER_STRING = "mainImageContainer";
	private static FeatureDefinition fdefinition;


	public FeatureDefinitionBuilder() {
		//definition = FeatureDefinition.getInstance();
	}

	public FeatureDefinition buildFromCSV() {
		String fileName = Settings.FEATURE_DEF_CSV;
		File DefinitionFile = new File(fileName);
		if (DefinitionFile.exists()) {
			List<String[]> featureSettings = PlayerUtilities.getArrayFromCSVFile(fileName);
			fdefinition = FeatureDefinition.getInstance();
			applySettingsToFeatureDefnition(featureSettings);
		}
		return fdefinition;
	}

	private void applySettingsToFeatureDefnition(List<String[]> featureSettings) {
		try 
		{
			String[] columnNames = featureSettings.remove(0);

			int idx_featureId 			= 0;
			int idx_featureType 		= 0;
			int idx_numberOfDaysToPlay 	= 0;
			int idx_containerID 		= 0;
			int idx_orientation 		= 0;
			int idx_unit 				= -1;
			int idx_option1 			= 0;

			for(int a = 0; a < columnNames.length; a++)
			{
				if(columnNames[a].equals("featureId")){
					idx_featureId = a;
				}
				else if(columnNames[a].equals("featureType")){
					idx_featureType = a;
				}
				else if(columnNames[a].equals("numberOfDaysToPlay")){
					idx_numberOfDaysToPlay = a;
				}
				else if(columnNames[a].equals("containerID")){
					idx_containerID = a;
				}
				else if(columnNames[a].equals("orientation")){
					idx_orientation = a;
				}
				else if(columnNames[a].equals("unit")){
					idx_unit = a;
				}
				else if(columnNames[a].equals("format")){
					idx_option1 = a;
				}
				else
				{
					System.out.print("FEATURE COLUMN ERROR!!!"+columnNames[a]);
				}
				
				System.out.println(a+", "+columnNames[a]);
			}

			List<FeatureContainerDefinition> definitionlist = new ArrayList<FeatureContainerDefinition>();
			
			try
			{
				if(fdefinition.getDefinition()!= null)
				{
					definitionlist = fdefinition.getDefinition();
				}
			}
			catch(Exception e)
			{
				definitionlist = new ArrayList<FeatureContainerDefinition>();
			}
			
			
			
			String jsonstringdate = "";
			String jsonstringweather = "";
			
			//System.out.println(featureSettings.size());
			
			for(int i = 0; i < featureSettings.size(); i++) {

				String[] record = featureSettings.get(i);
				FeatureContainerDefinition cdefinition = new FeatureContainerDefinition();

				cdefinition.setFeatureId(Integer.parseInt(record[idx_featureId]));
				cdefinition.setFeatureType(record[idx_featureType]);
				cdefinition.setNumberOfDaysToPlay(Integer.parseInt(record[idx_numberOfDaysToPlay]));
				cdefinition.setContainerID(Integer.parseInt(record[idx_containerID]));
				cdefinition.setOrientation(Integer.parseInt(record[idx_orientation]));
				
				//System.out.println(cdefinition);
				//System.out.println(definitionlist.size());
				if(idx_unit == -1)
				{
					cdefinition.setUnit("F");
				}
				else
				{
					cdefinition.setUnit(record[idx_unit]);
				}
				
				int cindex = isDefnitionExists(definitionlist,record[idx_containerID].trim());
				if(cindex == -1)
				{
					if(cdefinition != null)
					{
						definitionlist.add(cdefinition);
					}
				}
				else
				{
					definitionlist.remove(cindex);
					if(definitionlist != null)
					{
						if(cdefinition != null)
						{
							definitionlist.add(cdefinition);
						}
					}
				}
				
				//System.exit(1);
				if(record[idx_featureType].equals("DATE") && jsonstringdate.trim().equals(""))
					jsonstringdate = record[idx_option1];
				
				if(record[idx_featureType].equals("WEATHER") && jsonstringweather.trim().equals(""))
					jsonstringweather = record[idx_option1];
			}

			fdefinition.setDefinition(definitionlist);
			
			String existWeatherJsonString = "";
			String existDateJsonString = "";
			
			if(fdefinition != null)
			{
				if(fdefinition.getTextFormatMapper()!= null)
				{
					try {
						FieldFormatMapper formatm = fdefinition.getTextFormatMapper();

						existWeatherJsonString = formatm.get("option").toString();
						existDateJsonString = formatm.get("format").toString();
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						existWeatherJsonString = "";
						existDateJsonString = "";
					}
				}
			}
			
			FieldFormatMapper frm = new FieldFormatMapper();
			JSONParser parser = new JSONParser();
			
			if(!jsonstringdate.trim().equals(""))
			{
				frm.put("format", (JSONObject) parser.parse(jsonstringdate));
				
			}
			else
			{
				if(existDateJsonString.trim().equals(""))
				{
					frm.put("format", (JSONObject) parser.parse("{\"font-align\":\"Left\",\"color\":\"2B2B2B\",\"dateformat\":\"\",\"font\":\"Arial\",\"font-size\":\"12\"}"));
				}
				else
				{
					frm.put("format", (JSONObject) parser.parse(existDateJsonString));
				}
			}
			
			if(!jsonstringweather.trim().equals(""))
			{
				frm.put("option", (JSONObject) parser.parse(jsonstringweather));
				
			}
			else
			{
				if(existWeatherJsonString.trim().equals(""))
				{
					frm.put("option", (JSONObject) parser.parse("{\"font-align\":\"Left\",\"color\":\"2B2B2B\",\"dateformat\":\"\",\"font\":\"Arial\",\"font-size\":\"12\"}"));
				}
				else
				{
					frm.put("option", (JSONObject) parser.parse(existWeatherJsonString));
				}
			}
			
			fdefinition.setTextFormatMapper(frm);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			LoggingUtils.log(Level.SEVERE, "from feature definition builder class method  .applySettingsToFeatureDefnition " + e.getMessage(),e);
		}
	}
	
	private int isDefnitionExists(List<FeatureContainerDefinition> definitionlists, String ID)
	{
		int index = -1;
		try {
			int containerID = Integer.parseInt(ID);
			if (definitionlists != null) {
				if (definitionlists.size() > 0) {
					for (FeatureContainerDefinition def : definitionlists) {
						if (def.getContainerID() == containerID) {
							System.out.println("DEFINITION FOUND"+definitionlists.indexOf(def));
							index = definitionlists.indexOf(def);
							return index;
						}
					}
				}
			}
		} catch (Exception e) {
			LoggingUtils.log(Level.SEVERE, "from feature definition builder class method  isDefnitionExists " + e.getMessage());
			return index;
		}
		//System.out.println("NO DEFINITION FOUND");
		return index;
	}
	
	public static void main(String[] args) {
		
		new FeatureDefinitionBuilder().buildFromCSV();
		//PlayerUtilities.saveObjectToXMLFile("resources/feature_def1.xml", new FeatureDefinitionBuilder().buildFromCSV());

	}
}
